import { IMenusState, IEvent, IMenu } from "./model";
import { selectFolder } from "../utils/file-util";
import { dispatch as appDispatch } from './app-state';

function init (e: IEvent, s: IMenusState): IMenusState {
  let i = 0;
  const createId = () => `${Date.now()}_${i++}`;
  return {
    menus: [
      {
        id: createId(),
        text: 'File',
        children: [
          {
            id: createId(),
            text: 'Open Folder',
            command: 'open_folder'
          }
        ]
      }
    ],
    selectedMenus: [],
  };
}

function onMenusSelected (e: IEvent, s: IMenusState): IMenusState {
  const menus: IMenu[] = e.data;
  const lastMenu = menus[menus.length - 1];
  if (lastMenu.command == 'open_folder') {
    selectFolder().then(filePath => {
      appDispatch({
        type: 'folder.open',
        data: filePath,
      });
    });
    return {
      ...s,
      selectedMenus: [],
    }
  }
  return {
    ...s,
    selectedMenus: menus,
  }
}

function onMenusClean (e: IEvent, s: IMenusState): IMenusState {
  if (s.selectedMenus.length > 0) {
    return {
      ...s,
      selectedMenus: []
    };
  }
  return s;
}

export function dispatch (e: IEvent, s: IMenusState): IMenusState {
  if (e.type == 'app.init') {
    return init(e, s);
  } else if (e.type == 'menus.selected') {
    return onMenusSelected(e, s);
  } else if (e.type == 'menus.clean') {
    return onMenusClean(e, s);
  } else {
    return s;
  }
}

